import React, { useState, useRef, useEffect } from 'react';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { t } from '@lingui/macro';
import { Button, Dialog, Drawer, Message, Tab, Checkbox } from '@alifd/next';
import { useStore } from '@/hooks';
import { uniqueId } from 'lodash';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import CrossForm from './components/CrossForm';
import MainlandForm from './components/MainlandForm';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';

const tableId = uniqueId('tauTable-');
const { confirm } = Dialog;

const tabItems = [
  { key: '0', label: t`跨境车` },
  { key: '1', label: t`内地车` },
];

const crossTitle = {
  cross: t`添加跨境车辆`,
  editCross: t`修改跨境车辆`,
  viewCross: t`查看跨境车辆`,
};

const mainlandTitle = {
  mainland: t`添加大陆车辆`,
  editMainland: t`修改大陆车辆`,
  viewMainland: t`查看大陆车辆`,
};

const Vehicle = ({ queryParams }) => {
  const { vehicleStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const [showOrders, setShowOrders] = useState(false);
  const [counts, setCounts] = useState([]);

  const vehicleRef = useRef();

  useEffect(() => {
    (async () => {
      await store.getCompany();
    })();
  }, []);

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const res = await fetchOrderCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showOrders, store.vehicles]);

  async function fetchOrderCounts() {
    const promiseAry = store.vehicles.map((p) =>
      store.api
        .ccOrderCount({
          search: {
            vehicleId: p.id,
          },
        })
        .then((r) => ({ id: p.id, count: r })),
    );
    return Promise.all(promiseAry);
  }

  const handleOnSearch = (params) => {
    const { getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      from,
      to,
      ...queryParams,
      ...searchArgs,
    };
  };

  /**
   * @description 添加跨境车
   */
  const handleOpenAddCross = () => {
    vehicleRef.current = {};
    setModal(['cross']);
  };

  /**
   * @description 添加内地车
   */
  const handleOpenAddMainland = () => {
    vehicleRef.current = {};
    setModal(['mainland']);
  };

  /**
   * @description 修改车辆
   * @param {*} vehicle
   */
  const handleOpenEdit = (vehicle) => {
    vehicleRef.current = vehicle;
    let modalText;
    if (vehicle.licenseNo['hk']) {
      modalText = 'editCross';
    } else {
      modalText = 'editMainland';
    }
    setModal([modalText]);
  };

  /**
   * @description 查看车辆
   * @param {*} vehicle
   */
  const handleOpenCheck = (vehicle) => {
    vehicleRef.current = vehicle;
    let modalText;
    if (vehicle.licenseNo['hk']) {
      modalText = 'viewCross';
    } else {
      modalText = 'viewMainland';
    }
    setModal([modalText]);
  };

  /**
   * @description 删除车辆
   * @param {*} id
   */
  const handleDeleteVehicle = (id) => {
    confirm({
      title: '确认删除该车辆吗?',
      onOk() {
        return store.deleteVehicle(id);
      },
    });
  };

  /**
   * 关闭侧边卡片
   */
  const handleCancel = () => {
    setModal([]);
  };

  /**
   * 新建车辆
   * @param {*} result
   */
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  /**
   * 修政车辆
   * @param {*} result
   */
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  /**
   * 查看包车订单
   * @param {*} r
   */
  const handleOpenVehicle = (r) => {
    vehicleRef.current = r;
    setModal(['ccOrder']);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-addCross',
            title: t`添加跨境车`,
            type: 'primary',
            onClick: handleOpenAddCross,
          },
          {
            name: 'btn-addMainland',
            title: t`添加内地车`,
            type: 'primary',
            onClick: handleOpenAddMainland,
          },
        ]}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`更新开始时间`, t`更新结束时间`],
            },
          },
          {
            name: 'status',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.status),
              placeholder: t`状态`,
            },
          },
          {
            name: 'inlandVehicle',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.vehicleType),
              placeholder: t`车辆类型`,
            },
          },
        ]}
        keywordSearch={{
          // enabled: false,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          activeKey={store.orderStatus}
          onChange={(v) => {
            store.orderStatus = v;
          }}
          extra={<Checkbox onChange={(v) => setShowOrders(v)}>{t`查看订单`}</Checkbox>}
        >
          {tabItems.map((item) => (
            <Tab.Item key={item.key} title={item.label} />
          ))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.vehicles)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('company.name', { width: 88 }),
            column('licenseNo.mainland', { width: 88 }),
            column('licenseNo.hk', { width: 88 }),
            column('brandModelName', { width: 88 }),
            column('portNames', { width: 88 }),
            column('dateOfDelivery', { width: 88 }),
            column('mainDriverName', { width: 88 }),
            column('coDriverNames', { width: 88 }),
          ]
            .concat(
              global.isAdmin
                ? [
                    column('ccOrderNum', {
                      width: 88,
                      cell: (v, _, r) => (
                        <Button type="primary" text onClick={() => handleOpenVehicle(r)}>
                          {counts.find((p) => p.id === r.id)?.count || 0}
                        </Button>
                      ),
                    }),
                  ]
                : [],
            )
            .concat([
              column('status', { width: 88 }),
              column('upDate', { width: 88 }),
              {
                title: t`操作`,
                dataIndex: 'customerNumber',
                width: 180,
                cell: (_, __, vehicle) => (
                  <>
                    <Button text type="primary" onClick={() => handleOpenCheck(vehicle)}>{t`查看`}</Button>
                    <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                    <Button text type="primary" onClick={() => handleOpenEdit(vehicle)}>{t`编辑`}</Button>
                    <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                    <Button
                      text
                      type="primary"
                      style={{ color: 'red' }}
                      onClick={() => handleDeleteVehicle(vehicle?.id)}
                    >{t`删除`}</Button>
                  </>
                ),
              },
            ])
            .filter((c) => c.dataIndex !== 'ccOrderNum' || showOrders)}
        />
      </div>
      <Drawer
        visible={modal[0] === 'cross' || modal[0] === 'editCross' || modal[0] === 'viewCross'}
        title={crossTitle[modal[0]]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <CrossForm
          vehicleInfo={vehicleRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'editCross' ? handleUpdate : handleCreate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'mainland' || modal[0] === 'editMainland' || modal[0] === 'viewMainland'}
        title={mainlandTitle[modal[0]]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <MainlandForm
          vehicleInfo={vehicleRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'editMainland' ? handleUpdate : handleCreate}
        />
      </Drawer>
      <ComponentsDrawer
        modal={modal}
        name={vehicleRef.current?.id}
        queryParams={{ vehicleId: vehicleRef.current?.id }}
        onCancel={handleCancel}
      />
    </TauPage>
  );
};

export default observer(Vehicle);
